package user_service

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/utils/random"
)

func (UserService) HasUser(rs ctype.RegisterSource, val string) (user models.UserModel, ok bool) {

	query := global.DB.Where("")
	switch rs {
	case ctype.EmailRegister:

		query.Where("email=?", val)
	}
	err := global.DB.Where(query).Take(&user).Error
	if err != nil && err == gorm.ErrRecordNotFound {
		ok = false
		return

	}
	ok = true
	return
}

func (u UserService) UserCreate(rs ctype.RegisterSource, val string) (user models.UserModel, err error) {
	user = models.UserModel{
		Nickname:       fmt.Sprintf("木子AI用户_%s", random.RandString(4)),
		Username:       fmt.Sprintf("木子AI_%s", random.RandString(10)),
		Role:           ctype.AuthRole,
		RegisterSource: rs,
	}
	switch rs {
	case ctype.EmailRegister:
		user.Email = val
	case ctype.TelRegister:
		user.Tel = val
	}

	err = global.DB.Create(&user).Error
	if err != nil {
		logrus.Error(err)
		err = errors.New("用户注册失败,请联系管理员")
		return
	}
	u.UserScope(global.DB, user.ID, global.Config.AI.RegisterUserScope)
	logrus.Info("用户创建成功")
	return
}
